<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/27
 * Time: 13:39
 */

namespace app\admin\controller;


use app\admin\model\AdminMenu;
use app\admin\model\AdminRole;

class RoleController extends BaseController
{

    public function roleList(){
        $role = AdminRole::paginate(10)->each(function ($item){
            $item && $item->rule && $item->rule = json_decode($item->rule);
            $rule = AdminMenu::where('id','in',$item->rule)->field('menu_name')->select()->toArray();
            $str = implode(',',array_column($rule,'menu_name'));
            $item->rule =$str;
        });
        $this->assign('data',$role);
        return $this->fetch();
    }


    public function roleAdd(){
        $id = (int)input('get.id');
        $role = AdminRole::where('id',$id)->find();
        $role && $role['rule'] && $role['rule'] = json_decode($role['rule']);
        $this->assign('role',$role);
        $data = AdminMenu::select()->toArray();
        $results = $this->roleArray($data);
        $this->assign('data',$results);
        return $this->fetch();
    }

    public function RoleSave(){
        $id = (int)input('post.id');
        $data['role_name'] = trim(input('post.role_name'));
        $menus = input('post.menu/a');
        $status = (int)input('post.status');
        if(!$data['role_name']){
            return json(['code'=>0,'msg'=>'角色名称不能为空']);
        }
        $menus && $data['rule'] = json_encode(array_keys($menus));
        $data['status'] = $status;
        if($id){
            AdminRole::update($data,['id'=>$id]);
        }else{
            AdminRole::create($data);
        }
        return json(['code'=>1,'msg'=>'保存成功']);
    }


    public function roleDel(){
        $id = input('post.id');
        $ret = AdminRole::destroy($id);
        if (!$ret){
            return json(['code'=>0,'msg'=>'删除失败']);
        }
        return json(['code'=>1,'msg'=>'删除成功']);
    }



    private function formatMenus($items,&$res = array()){
        foreach($items as $item){
            if(!isset($item['children'])){
                $res[] = $item;
            }else{
                $tem = $item['children'];
                unset($item['children']);
                $res[] = $item;
                $this->formatMenus($tem,$res);
            }
        }
        return $res;
    }

}